import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.captcha.v20190722 import captcha_client, models
from django.conf import settings


class TencentCloudAPI(object):
    """腾讯云API操作工具类"""

    def __init__(self):
        # 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        # 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        # self.cred = credential.Credential("SecretId", "SecretKey")
        self.cred = credential.Credential(settings.TENCENTCLOUD['SecretId'], settings.TENCENTCLOUD['SecretKey'])

    def captcha(self, ticket, randstr, user_ip):
        try:
            Captcha = settings.TENCENTCLOUD["Captcha"]

            # 实例化一个http选项，可选的，没有特殊需求可以跳过
            httpProfile = HttpProfile()
            # 设置API所在服务器域名
            httpProfile.endpoint = Captcha['endpoint']

            # 实例化一个client选项，可选的，没有特殊需求可以跳过
            clientProfile = ClientProfile()
            # 给客户端绑定请求的服务端域名
            clientProfile.httpProfile = httpProfile

            # 实例化要请求产品的client对象,clientProfile是可选的
            client = captcha_client.CaptchaClient(self.cred, "", clientProfile)

            # 实例化一个请求对象,每个接口都会对应一个request对象
            req = models.DescribeCaptchaResultRequest()

            params = {
                "CaptchaType": Captcha['CaptchaType'],  # 验证码类型固定为9
                "Ticket": ticket,  # 客户端提交的临时票据
                "UserIp": user_ip,  # 客户端ip地址
                "Randstr": randstr,  # 随机字符串
                "CaptchaAppId": Captcha['CaptchaAppId'],  # 验证码应用ID
                "AppSecretKey": Captcha['AppSecretKey'],  # 验证码应用key
            }

            # 发送请求
            req.from_json_string(json.dumps(params))

            # 获取腾讯云的响应结果,返回的resp是一个DescribeCaptchaResultResponse的实例，与请求对象对应
            resp = client.DescribeCaptchaResult(req)
            # 把响应结果转换成json格式数据,输出json格式的字符串回包
            result = json.loads(resp.to_json_string())  # 反序列化
            return result and result.get("CaptchaCode") == 1

        except TencentCloudSDKException as err:
            # print(err)
            raise TencentCloudSDKException
